Ext.namespace('VAS');
var hiddenValues={};
var searchPanelValuse={};
//VAS.BindGridButton = Ext.extend(Ext.Button, {
//		initComponent : function() {
//			
//			var _this = this;
//			var _text = this.fieldLabel;
//			this.fieldLabel = "";
//
//			var thisConfig = {
////				id:'bindGridButton',
//				anchor    : '30%',
//				align     : 'center',
//				text      : _text,
//				handler   : this.submitQuery
//			};
//			
//			this.addEvents('submitQuery');
//			this.on('submitQuery',this.submitQuery);
//			Ext.apply(this, thisConfig);
//			Ext.apply(this.initialConfig, thisConfig);
//			VAS.BindGridButton.superclass.initComponent.apply(this,arguments);
//
//		}
//	,submitQuery:function(){
//			
//			var _form = this.ownerCt.ownerCt.ownerCt;
//			
//			if (_form.getForm().isValid()) {
//				var gridStore = Ext.StoreMgr.lookup(Global.STD_GRID_STORE.id);
//				var _params = {
//					"start"          : 0,
//					"limit"          : 10,
//					"searchPanelId"  : _form.id, 
//					"gridPanelId"    : gridStore.baseParams.gridPanelId 
//				};
//
//				Ext.apply(_params,_form.getForm().getValues());
//				Ext.apply(_params,hiddenValues);						
//				Ext.apply(gridStore.baseParams,_params);
//			
//				gridStore.load();
//			}
//	}
//
//})
//
//Ext.reg('bindGridButton', VAS.BindGridButton);

VAS.DynamicItems = function($config) {
	var  _this  = this;
	var thisConfig={
			keys : {
			key : 13, // or 13
			fn : function() {					
				if (this.getForm().isValid()) {
				var gridStore = Ext.StoreMgr.lookup('popUp_grid_store_'+$config.gridId);		
				if(typeof(gridStore)=='undefined'){				
					  gridStore=Ext.StoreMgr.itemAt(0);
				}				
				this.baseParams.searchPanelId = this.id;
				this.baseParams.gridPanelId   = gridStore.baseParams.gridPanelId;	
				this.baseParams.limit   = gridStore.baseParams.limit;					
				
				
				Ext.apply(this.baseParams,this.getForm().getValues());	
			
				Ext.apply(gridStore.baseParams,this.baseParams);
				gridStore.load();
			} 
             
			},
			scope : this
		}  
	}
	Ext.apply($config, thisConfig);
//	Ext.apply(this.initialConfig, thisConfig);
//	this.config = config;
	VAS.DynamicItems.superclass.constructor.call(this, $config);
}

Ext.extend(VAS.DynamicItems, Ext.FormPanel, {
    /**
     * 组件面板的宽度, 默认值是85%
     */
    cpWidth : .8,
    /**
     * 按钮面板的宽度, 默认值是15%
     */
    bpWidth : .2,	
    
    minButtonWidth : 50,
    
    
    frame  : false,
    
    border : false,
    
    cw     : .25,

    lw     : 80,
    
    maxCols : 3,
    
    hiddenCmps : [],
    /**
     * 封装待布局的组件数组
     */
    cmps : [],    
    
	baseParams : {
		"start"          : 0,
		"limit"          : 10,
		"searchPanelId"  : "searchPanelId", 
		"gridPanelId"    : "gridPanelId" 
	},
	
	submitQuery:function(button){
		
    		var _form = this.ownerCt.ownerCt.ownerCt.ownerCt;
			if (_form.getForm().isValid()) {
				var gridStore = Ext.StoreMgr.lookup('popUp_grid_store_'+_form.gridId);
			
				if(typeof(gridStore)=='undefined'){
//					gridStore = Ext.StoreMgr.lookup(Global.STD_GRID_STORE.id);
				
					  gridStore=Ext.StoreMgr.itemAt(0);
					
//						alert('2'+Ext.StoreMgr.getCount());
				}
				
				_form.baseParams.searchPanelId = _form.id;
				_form.baseParams.gridPanelId   = gridStore.baseParams.gridPanelId;
						_form.baseParams.limit   = gridStore.baseParams.limit;	
//				_form.baseParams.limit=
				Ext.apply(_form.baseParams,_form.getForm().getValues());
//				Ext.apply(_form.baseParams,hiddenValues);						
				Ext.apply(gridStore.baseParams,_form.baseParams);
				gridStore.load();
			}    		
    	
	},
	
    btns : [{
    	xtype    : "button",
    	text     : "查询",
    	handler  : function() {
    		var _form = this.ownerCt.ownerCt.ownerCt.ownerCt;
			if (_form.getForm().isValid()) {
				var gridStore = Ext.StoreMgr.lookup('popUp_grid_store_'+_form.gridId);
				if(typeof(gridStore)=='undefined'){
//					gridStore = Ext.StoreMgr.lookup(Global.STD_GRID_STORE.id);
				
					  gridStore=Ext.StoreMgr.itemAt(0);
				}
				
				_form.baseParams.searchPanelId = _form.id;
				_form.baseParams.gridPanelId   = gridStore.baseParams.gridPanelId;
				_form.baseParams.limit   = gridStore.baseParams.limit;	
				
				var formValues = _form.getForm().getValues();
				
				//时间段查询时，增加开始时间不能大于结束时间的校验
			    for(var prop in formValues){
			    	if(prop.replace(/(^\s+)|(\s+$)/g,"").indexOf('date_after_') > -1){
			    		var date_after_value = formValues[prop]
			    		var date_before_prop = 'date_before_' + prop.replace('date_after_','');
			    		var date_before_value = formValues[date_before_prop];
			    		if(date_before_value=='undefined' || date_before_value==''){
			    			break;
			    		}
			    		if(date_after_value=='undefined' || date_after_value==''){
			    			break;
			    		}
			    		if(date_before_value > date_after_value){
			    			Ext.Msg.alert('提示', '开始时间不能大于结束时间!');
			    			return;
			    		}
			    	}
			    }
			    
				Ext.apply(_form.baseParams,_form.getForm().getValues());
//				Ext.apply(_form.baseParams,hiddenValues);						
				Ext.apply(gridStore.baseParams,_form.baseParams);
				gridStore.load();
			}
    	}
    },{
    	xtype    : "button",
    	text     : "清空",
    	handler  : function() {
    		var _form = this.ownerCt.ownerCt.ownerCt.ownerCt;
    		_form.getForm().reset();
    	}
    }],
	

    
    initColumnWidth  : function(){
    	this.cw = Math.round((1/this.maxCols)*100)/100;
    },
	
	initLayout : function() {
        // 定义组件面板, 用于装提供查询条件的组件
        var cmpsPanel = new Ext.Panel({
            columnWidth : this.cpWidth,
            border      : false,
            layout      : 'column'
        });

        // 定义按钮面板, 用于装查询, 清除之类的按扭
        var bpConfig = {
            columnWidth : this.bpWidth,
            buttonAlign : 'right',
            minButtonWidth : this.minButtonWidth
        };	
        
        // 修正样式以兼容IE和Firefox
        var offsetMargin = new Number(this.cmps.length - this.hiddenCmps.length - 1) / new Number(this.maxCols);
        offsetMargin = parseInt(offsetMargin) * 25;
        if (Ext.isIE) {
            bpConfig.style = 'margin-top: ' + (-15 + offsetMargin);
        } else {
            bpConfig.style = 'margin-top: -3';
        }
         
        // 定义按钮面板, 用于装查询, 清除之类的按扭
        var btnsPanel = new Ext.Panel(bpConfig);
        
        // 设置查询主面板布局, 并将组件面板和按钮面板放入其中
        this.layout = 'fit';
        this.items = [{
            xtype  : 'panel',
            layout : 'column',
            frame  : true,
            border : false,
            items  : [cmpsPanel,btnsPanel]
        }];    
        
        // 组件面板中组件的布局处理
        for (var i = 0; i < this.maxCols; i++) {
            // 每列的子Panel面板定义
            var panel = new Ext.Panel({
            	style : "margin:5px 0px 0px 0px",
                columnWidth : this.cw,
                labelWidth  : this.lw,
                border      : false,
                layout      : 'form'
            });
            
            // 添加控件到子Panel中
            for (var j = i; j < this.cmps.length; j += this.maxCols) {
                panel.add(this.cmps[j]);
            }
            cmpsPanel.add(panel);
        }    
       
        
                // 放置按钮到按钮面板中
        for (var i = 0; i < this.btns.length; i++) {
            btnsPanel.addButton(this.btns[i]);
        }
	
	},
	
	initFieldSet : function($url) {
		var fieldSetItem = SyncAjax($url,{
			"searchPanelId"    : this.id
			,'entryMenuId'	:	this.menuId + ''
		});
		
		this.hiddenCmps = [];
		this.cmps = [];
		var items = fieldSetItem.fieldSet.items;
		for (var i = 0;i < items.length;i++) {
			if(items[i].xtype === 'hidden') {
				this.hiddenCmps.push(items[i]);
			} else {
				this.cmps.push(items[i]);
			}
		}
		for (var j = 0;j < this.hiddenCmps.length; j++) {
			this.cmps.push(this.hiddenCmps[j]);
		}
		this.labelWidth = fieldSetItem.fieldSet.labelWidth;
		this.maxCols    = fieldSetItem.fieldSet.maxCols;
	},
	
	initComponent : function() {
		
		// 初始化数据
		this.initFieldSet(this.url);
		// 初始化列
		this.initColumnWidth();
		// 初始化面板
		this.initLayout();
		
		VAS.DynamicItems.superclass.initComponent.apply(this, arguments);	
	}
	
	,onRender : function(ct, position) {
		var _this=this;
		VAS.DynamicItems.superclass.onRender.call(this, ct, position);	
		
		var gridStore = Ext.StoreMgr.lookup('popUp_grid_store_'+this.gridId);
		if(typeof(gridStore)=='undefined'){
			  gridStore=Ext.StoreMgr.itemAt(0);
		}
		//把id赋给grid，供grid用
		gridStore.searchPanelId=this.id;
	}
	
	
/* 
	initComponent : function() {
		var _this = this;
		_this.hiddenValues={},
		_this.$fieldSet = {};
		_this.getFieldSet = function($url) {
			var fieldSetItem = SyncAjax($url,{
				"searchPanelId"    : this.id
			});
			return fieldSetItem.fieldSet;
		}
		_this.$fieldSet = _this.getFieldSet(this.url);		
		
			var _items=[];
			var _dispalyItems=[];
			
			for(var i=0;i<_this.$fieldSet.items.length;i++){
				if(_this.$fieldSet.items[i].xtype==='hidden'){					
//				
					var name=_this.$fieldSet.items[i].name;
					var value=_this.$fieldSet.items[i].value;
					eval("hiddenValues."+name+"="+'value');
				}else{
					_dispalyItems.push(_this.$fieldSet.items[i]);
				}
				
			}

			
			_items.push(new Ext.ux.FieldSet({
							columnWidth    : _this.$fieldSet.columnWidth,
							labelWidth     : _this.$fieldSet.labelWidth,
							title          : _this.$fieldSet.title,								
	                        fieldSetItems  : _dispalyItems

						}));
			
		_this.queryButton=new VAS.BindGridButton({fieldLabel:'   查        找     '});
		//根据要显示的items的个数计算columnWidth
		var itemsNumber = _dispalyItems.length;
		var fieldWidth = itemsNumber*0.3;
		var buttonWidth = 1 - fieldWidth;
		
		var thisConfig = {		
		
			frame   : true,
			layout : "column",
			columnWidth : 1,
			border : false,
			items : [{
								layout : 'column',
								columnWidth : 1,
								items : [{
											cls : 'query-align',
											columnWidth : fieldWidth,
											items : _items
										}, {
											cls : 'query-align',
											columnWidth : buttonWidth,
											defaults : {	
												layout : 'form'
//												labelWidth:50,
//												columnWidth : 50,
//												defaults : {
//													anchor : '90%'
//												}
											},
											items : _this.queryButton
										}]
							}],

			  		keys : {
			key : 13, // or 13
			fn : function() {					
	           _this.queryButton.fireEvent('submitQuery',_this.queryButton);
				
             
			},
			scope : this
		}  
		};

		Ext.apply(this, thisConfig);
		Ext.apply(this.initialConfig, thisConfig);
		VAS.DynamicItems.superclass.initComponent.apply(this, arguments);
	}*/
})

VAS.DynamicQueryWindow = function($config) {
	var _this = this;
	
	_this._getWinHeight = function(_height) {
		var $height;
		if (typeof(_height) === "string") {
			if (_height.indexOf('%') > -1) {
				var percent = _height.substring(0, _height.length - 1) / 100;
					$height = document.body.clientHeight -_y-122;	
			} else {
				$height = _height ;
			}
		} 
		return $height;

	};
	
	_this._getWinWidth = function(_width,_x) {			
		var $width;
		if (typeof(_width) !== "undefined") {
			if (typeof(_width)==='string'&&_width.indexOf('%') > -1) {
			$width = document.body.clientWidth -_x-130;	
			} else if(typeof(_width)==='number'){
				$width = _width;
			}
		} 
		return $width;
	};
	var dynamicFormPanel = new VAS.DynamicItems({
		url    : $config.formPanel.url,
		id     : $config.formPanel.id,
		menuId : $config.menuid
	})
	var thisConfig = {
		layout:'fit',
		items : dynamicFormPanel
//		,height : _this._getWinHeight($config)
		,width     : _this._getWinWidth($config.width,$config.x)
	};
	var _config = $config || {};

	Ext.apply(_this, Ext.apply(_config, thisConfig));
	VAS.DynamicQueryWindow.superclass.constructor.call(_this);

};

Ext.extend(VAS.DynamicQueryWindow, VAS.BasicWindow, {});
Ext.reg('dynamicQuery-win', VAS.DynamicQueryWindow);
